<?php
namespace app\common\component\message;

class MessageService {
	public function getMessages($page = 10, $simple = false) {
		return (new MessageModel()) -> where('user_id', \think\Session::get('user_id')) -> order('reply_time DESC') -> paginate($page, $simple);	
	}

	public function getAll($page = 10) {
		return (new MessageModel()) -> alias('m')
		-> join('league_user u', 'm.user_id = u.user_id')
		-> field(
			'm.message_id, m.title, m.content, m.create_time, m.reply_time, m.replay_content, ' .
			'u.username, u.realname, u.phone, u.bank_code'
		)
		-> order('m.reply_time ASC') -> paginate($page);
	}

	public function getMessage($message_id) {
		if($message_id <= 0) {
			$getMessage = MessageModel::order('message_id DESC') -> find();
		} else {
			$getMessage = MessageModel::get($message_id);
		}

		if($getMessage) {
			return [
				'code' => 0,
				'message' => 'Success',
				'data' => [
					'message' => $getMessage
				]
			];
		}
		return [
			'code' => -1,
			'message' => 'Fail'
		];
	}

	public function create($data) {
    	$messageModel = new MessageModel($data);

		// $messageModel -> allowField(true) -> save();
    	if($messageModel -> save()) {
    		return [
    			'code' => 0,
    			'message' => '留言创建成功',
    			'data' => [
    				'message' => $messageModel
    			]
    		];
    	}

    	return [
			'code' => -1,
			'message' => '留言创建失败'
		];
    }

	public function update($data, $message_id) {
		$messageModel = new MessageModel();

		$updateMessage = $messageModel -> where('message_id', $message_id) -> update($data);

    	if($updateMessage) {
    		return [
    			'code' => 0,
    			'message' => '留言修改成功'
    		];
    	}

    	return [
			'code' => -1,
			'message' => '留言修改失败'
		];
	}

	public function delete($message_id) {
		$getMessage = MessageModel::get($message_id);

    	if($getMessage -> delete()) {
    		return [
    			'code' => 0,
    			'message' => '留言删除成功'
    		];
    	}

    	return [
			'code' => -1,
			'message' => '留言删除失败'
		];
	}
}
?>